<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
//获得客户端IP
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false){
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
}

/**
 * 获取IP中文地址
 * @param string $ips ip地址
 * @return string 返回中文地址
 */
function get_ip_data($ip=''){
    if (empty($ip)) {
       return false;
    }
    if ($ip == '0.0.0.0' || $ip == '127.0.0.1' || $ip == '::1') {
        return "本地";
    }
    $ipadd = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);//根据新浪api接口获取
    if($ipadd) {
        $str = str_replace('1', '', $ipadd);
        $str = str_replace('-', '', $str);
        $str = trim($str);
        return $str;
    }else {
        return "未知";
    } 
}

/**
 * 公共json返回
 * @param integer $type 返回代码类型 0 成功 1失败
 * @param string $msg 文本信息
 * @param object $data 数据信息
 */
function return_json($code=0, $msg="", $data= null){
    $ret["code"]=$code;
    $ret['msg']=$msg;
    $ret['data'] = $data;
    return json($ret);
}

function check_permissioncode($code){
    $uid = Session('uid');
    $permissioncodes = Cache("permissioncodes_".$uid);
    return in_array($code,$permissioncodes);
}

function createToken($n = 'Token'){
    $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
    return session($n,authcode($code).'_'.time());
}

function authcode($str){
    $key = "ADMYIXIAOWAI";
    $str = substr(md5($str), 8, 10);
    return substr(md5($key . $str),2,5);
}

function checkToken($token,$n = 'Token'){
    if ($token == session('TOKEN')) {
        session('TOKEN', NULL);
        return TRUE;
    } else {
        return FALSE;
    }
}

/**
 * 获取访客操作系统
 */
function get_client_os(){
    if(!empty($_SERVER['HTTP_USER_AGENT'])) {
        $OS = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($OS, 'Android') !== false) {//strpos()定位出第一次出现字符串的位置，这里定位为0 
            preg_match("/(?<=Android )[\d\.]{1,}/", $OS, $version); 
            $OS ='Android '.$version[0];
        }elseif (strpos($OS, 'iPhone') !== false) { 
            preg_match("/(?<=CPU iPhone OS )[\d\_]{1,}/", $OS, $version); 
            $OS = 'iPhone iOS '.str_replace('_', '.', $version[0]); 
        }elseif (strpos($OS, 'iPad') !== false) { 
            preg_match("/(?<=CPU OS )[\d\_]{1,}/", $OS, $version); 
            $OS = 'iPad iOS '.str_replace('_', '.', $version[0]);  
        }elseif (preg_match('/win/i',$OS)) {
            $OS = 'Windows';
        }elseif (preg_match('/mac/i',$OS)) {
            $OS = 'MAC';
        }elseif (preg_match('/linux/i',$OS)) {
            $OS = 'Linux';
        }elseif (preg_match('/unix/i',$OS)) {
            $OS = 'Unix';
        }elseif (preg_match('/bsd/i',$OS)) {
            $OS = 'BSD';
        }else {
            $OS = 'Other';
        }
        return $OS; 
    }else {
        return false;
    }  
}

/**
 * 获取当前域名地址
 */
function get_host(){
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $host = "$protocol$_SERVER[HTTP_HOST]";
    return $host;
}

/**
 * 导出Excel
 */
function writer_excel($header, $data,$name=false,$type = 0) {
    //导出
    $result = import("PHPExcel",EXTEND_PATH.'PHPExcel');
    if(!$name){$name=date("Y-m-d-H-i-s",time());}
    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    //设置表头
    $key = ord("A");
    foreach($header as $v){
        $colum = chr($key);
        $objPHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->getRowDimension(1)->setRowHeight(20);
    foreach($data as $key => $rows){ //行写入
        $span = ord("A");
        foreach($rows as $keyName=>$value) {// 列写入
            $j = chr($span);
            $objActSheet->getRowDimension($column)->setRowHeight(20);
            $objActSheet->setCellValue($j.$column, $value);
            $span++;
        }
        $column++;
    }
    $objPHPExcel->getActiveSheet()->setTitle('chen.data');
    $objPHPExcel->setActiveSheetIndex(0);
    $fileName = iconv("utf-8", "gb2312", './Data/excel/'.date('Y-m-d_', time()).time().'.xls');
    $saveName = iconv("utf-8", "gb2312", $name.'.xls');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    if ($type == 0) {
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$saveName\"");
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
    } else {
        $objWriter->save($fileName);
        return $fileName;
    }

}

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length=6, $type='string', $convert=0){    
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );
    
    if(!isset($config[$type])) $type = 'string';
    $string = $config[$type];
    
    $code = '';
    $strlen = strlen($string) - 1;
    for($i = 0; $i < $length; $i++){
        $code .= $string{mt_rand(0, $strlen)};
    }
    if($convert !== 0){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}

/**
* 对数据进行转码，避免中文转json时乱码
* @param array & string $data
*/
function toJson($data) {
    $data = json_encode(urlencodeAry($data));
    return urldecode($data);
}

/**
* 将数据进行urlencode
* @param array & string $data
*/
function urlencodeAry($data) {
    if(is_array($data)) {
        foreach($data as $key=>$val) {
            $data[$key] = urlencodeAry($val);
        }
        return $data;
    } else {
        return urlencode($data);
    }
}